#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <getopt.h>

void print_help(char *name);

#define	SERV_STR "GFX"
int main(int argc, char **argv)
{
	int					rv = -1;
	int					servfd = -1;
	int					clifd = -1;
	int					port = 12345;
	char				buf[1024];
	struct sockaddr_in	cliaddr;
	socklen_t			cliaddr_len;
	struct sockaddr_in	servaddr;

	struct option		opts[] = {
		{"port", required_argument,	NULL, 'P'},
		{"help", required_argument, NULL, 'h'}
	};

	while( (rv = getopt_long(argc,argv, "p:h", opts, NULL)) != -1)
	{
		switch(rv)
		{
			case 'p' :
						port = atoi(optarg);
						break;
			case 'h' :
						print_help(argv[0]);
						return 0;

		}
	}
	
	servfd = socket(AF_INET, SOCK_STREAM, 0);
	if(servfd < 0)
	{
		printf(" socket error : %s \n", strerror(errno));
		return -1;

	}	

	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	servaddr.sin_addr.s_addr = htons(INADDR_ANY);

	rv = bind(servfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
	if(rv == -1)
	{
		printf(" bind error :%s \n ", strerror(errno));
		goto clear;
	}

	rv = listen(servfd, 13);
	if(rv == -1)
	{
		printf(" listen  error :%s \n ", strerror(errno));
		goto clear;
	}

	while(1)
	{
		printf(" [%d]start accept new \n", servfd);

		clifd = accept(servfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
		if(clifd < 0)
		{
			printf("accept error :%s \n", strerror(errno));
			continue;
		}
		
		while(1)
		{
			memset(buf, 0, sizeof(buf));
			rv = read(clifd, buf, sizeof(buf));
			if( rv < 0 )
			{
				printf("read error : %s \n", strerror(errno));
				close(clifd);
				break;
			}
			else if( rv == 0)
			{
				printf("connect break [%s : %d] \n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
				close(clifd);
				break;
			}
			else if( rv > 0)
			{
				printf("read succed  [%s : %d]  : %s\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port), buf);
				
				buf[strlen(buf)-1] = ' ';
				strcat(buf,	SERV_STR);

				rv = write(clifd, buf, strlen(buf));
				if(rv < 0)
				{
					printf(" write error : %s \n" , strerror(errno));
					close(clifd);
					continue;
				}

				printf(" write succed  : %s\n", buf);
			}
		}

	}
clear:
	close(clifd);
	close(servfd);

	return 0;
}



void print_help(char *name)
{
	printf("--port -p : ipv4 port \n --ip -i : addr \n");
}



